import React, { useState, useEffect } from 'react';
import { Box, Typography, Card, CardContent, Grid, Button as MuiButton, TextField, Dialog, DialogTitle, DialogContent, DialogActions, FormControl, InputLabel, Select, MenuItem, Chip, Checkbox, FormGroup, FormControlLabel } from '@mui/material';
import { NetworkCheck, DirectionsCar, AddCircle, Search, Refresh, Save, Cancel, ChevronRight } from '@mui/icons-material';
import { apiRequest } from '../utils/api';

// 使用原始Button组件
const Button = MuiButton;

const VehicleNetworking = () => {
  const [vehicleGroups, setVehicleGroups] = useState([]);
  const [allVehicles, setAllVehicles] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [userData, setUserData] = useState(null);
  const [selectedGroup, setSelectedGroup] = useState(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [openGroupDialog, setOpenGroupDialog] = useState(false);
  const [groupForm, setGroupForm] = useState({ name: '', description: '', groupType: '', memberVehicles: [], sharedPermissions: [] });
  const [availablePermissions, setAvailablePermissions] = useState([]);


  // 加载车辆数据函数
  const loadVehicleData = async () => {
    try {
      // 首先尝试从API获取数据
      try {
        // 获取用户车辆数据
        const vehiclesResponse = await apiRequest.get('/api/vehicles/my-vehicles');
        const vehiclesData = vehiclesResponse.data;
        setAllVehicles(vehiclesData);
        
        // 如果API返回的车辆数据为空或出错，则使用本地存储或模拟数据
        if (!vehiclesData || vehiclesData.length === 0) {
          throw new Error('No vehicles data from API');
        }
      } catch (apiError) {
        console.warn('API request failed, using local data:', apiError.message);
        
        // 在开发环境中使用模拟数据
        if (process.env.NODE_ENV === 'development') {
          // 加载所有车辆数据
          const storedVehicles = localStorage.getItem('vehicles');
          if (storedVehicles) {
            setAllVehicles(JSON.parse(storedVehicles));
          } else {
            const mockVehicles = generateMockVehicles();
            setAllVehicles(mockVehicles);
            localStorage.setItem('vehicles', JSON.stringify(mockVehicles));
          }
        }
      }
      
      // 加载车辆组数据
      const storedGroups = localStorage.getItem('vehicleGroups');
      if (storedGroups) {
        setVehicleGroups(JSON.parse(storedGroups));
      } else {
        const mockGroups = generateMockVehicleGroups();
        setVehicleGroups(mockGroups);
        localStorage.setItem('vehicleGroups', JSON.stringify(mockGroups));
      }
      
      // 加载可用权限数据
      const storedPermissions = localStorage.getItem('dataPermissions');
      if (storedPermissions) {
        setAvailablePermissions(JSON.parse(storedPermissions));
      } else {
        const mockPermissions = generateMockPermissions();
        setAvailablePermissions(mockPermissions);
        localStorage.setItem('dataPermissions', JSON.stringify(mockPermissions));
      }
      
      setError(null);
    } catch (err) {
      console.error('Failed to load vehicle networking data:', err);
      setError('Failed to load vehicle networking data. Please try again later.');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    // 获取用户信息
    const savedUserInfo = localStorage.getItem('userInfo');
    if (savedUserInfo) {
      try {
        const userInfo = JSON.parse(savedUserInfo);
        setUserData(userInfo);
      } catch (error) {
        console.error('Failed to parse user info:', error);
      }
    }

    // 加载车辆组和车辆数据
    setLoading(true);
    loadVehicleData();
  }, []);

  // 生成模拟车辆组数据
  const generateMockVehicleGroups = () => {
    const groups = [
      {
        id: 'group1',
        name: '物流车队A',
        description: '主要负责北京市内货物运输的车队',
        groupType: 'logistics',
        memberVehicles: ['vehicle1', 'vehicle2', 'vehicle3'],
        sharedPermissions: ['perm1', 'perm2'],
        createdAt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
        updatedAt: new Date().toISOString(),
        createdBy: 'admin'
      },
      {
        id: 'group2',
        name: '出租车队',
        description: '公司旗下的出租车运营团队',
        groupType: 'taxi',
        memberVehicles: ['vehicle4', 'vehicle5', 'vehicle6'],
        sharedPermissions: ['perm3'],
        createdAt: new Date(Date.now() - 14 * 24 * 60 * 60 * 1000).toISOString(),
        updatedAt: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString(),
        createdBy: 'admin'
      },
      {
        id: 'group3',
        name: '无人矿卡集群',
        description: '用于矿区作业的无人矿卡设备集群',
        groupType: 'mining',
        memberVehicles: ['vehicle7', 'vehicle8'],
        sharedPermissions: ['perm1', 'perm2', 'perm3'],
        createdAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
        updatedAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString(),
        createdBy: 'admin'
      },
      {
        id: 'group4',
        name: '高管专车组',
        description: '公司高管使用的专车组',
        groupType: 'executive',
        memberVehicles: ['vehicle9', 'vehicle10'],
        sharedPermissions: ['perm2', 'perm3'],
        createdAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString(),
        updatedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(),
        createdBy: 'admin'
      }
    ];
    return groups;
  };

  // 生成模拟车辆数据
  const generateMockVehicles = () => {
    const vehicles = [
      {
        id: 'vehicle1',
        licensePlate: '京A12345',
        type: '货车',
        brand: '福田',
        model: '欧曼',
        status: 'online',
        lastUpdated: new Date().toISOString(),
        location: { lat: 39.9042, lng: 116.4074 }
      },
      {
        id: 'vehicle2',
        licensePlate: '京B54321',
        type: '货车',
        brand: '东风',
        model: '天龙',
        status: 'online',
        lastUpdated: new Date().toISOString(),
        location: { lat: 39.9142, lng: 116.4174 }
      },
      {
        id: 'vehicle3',
        licensePlate: '京C67890',
        type: '货车',
        brand: '解放',
        model: 'J6',
        status: 'online',
        lastUpdated: new Date().toISOString(),
        location: { lat: 39.9242, lng: 116.4274 }
      },
      {
        id: 'vehicle4',
        licensePlate: '京D11111',
        type: '出租车',
        brand: '大众',
        model: '桑塔纳',
        status: 'online',
        lastUpdated: new Date().toISOString(),
        location: { lat: 39.9342, lng: 116.4374 }
      },
      {
        id: 'vehicle5',
        licensePlate: '京E22222',
        type: '出租车',
        brand: '现代',
        model: '伊兰特',
        status: 'online',
        lastUpdated: new Date().toISOString(),
        location: { lat: 39.9442, lng: 116.4474 }
      },
      {
        id: 'vehicle6',
        licensePlate: '京F33333',
        type: '出租车',
        brand: '丰田',
        model: '卡罗拉',
        status: 'online',
        lastUpdated: new Date().toISOString(),
        location: { lat: 39.9542, lng: 116.4574 }
      },
      {
        id: 'vehicle7',
        licensePlate: '京G44444',
        type: '矿卡',
        brand: '徐工',
        model: 'XE240',
        status: 'online',
        lastUpdated: new Date().toISOString(),
        location: { lat: 39.9642, lng: 116.4674 }
      },
      {
        id: 'vehicle8',
        licensePlate: '京H55555',
        type: '矿卡',
        brand: '三一',
        model: 'SY215',
        status: 'online',
        lastUpdated: new Date().toISOString(),
        location: { lat: 39.9742, lng: 116.4774 }
      },
      {
        id: 'vehicle9',
        licensePlate: '京J66666',
        type: '轿车',
        brand: '奔驰',
        model: 'S级',
        status: 'online',
        lastUpdated: new Date().toISOString(),
        location: { lat: 39.9842, lng: 116.4874 }
      },
      {
        id: 'vehicle10',
        licensePlate: '京K77777',
        type: '轿车',
        brand: '宝马',
        model: '7系',
        status: 'online',
        lastUpdated: new Date().toISOString(),
        location: { lat: 39.9942, lng: 116.4974 }
      }
    ];
    return vehicles;
  };

  // 生成模拟权限数据
  const generateMockPermissions = () => {
    const permissions = [
      {
        id: 'perm1',
        name: '维修数据访问',
        description: '允许访问车辆维修记录、保养信息等',
        attributes: [
          { name: 'maintenance', value: 1 },
          { name: 'repair', value: 1 }
        ],
        accessPolicy: 1
      },
      {
        id: 'perm2',
        name: '运行数据访问',
        description: '允许访问车辆行驶数据、发动机状态等',
        attributes: [
          { name: 'operation', value: 1 },
          { name: 'real-time', value: 1 }
        ],
        accessPolicy: 1
      },
      {
        id: 'perm3',
        name: '行车记录访问',
        description: '允许访问行车记录仪数据、GPS轨迹等',
        attributes: [
          { name: 'tracking', value: 1 },
          { name: 'privacy', value: 0 }
        ],
        accessPolicy: 1
      }
    ];
    return permissions;
  };

  // 打开添加/编辑车辆组对话框
  const handleOpenGroupDialog = (group = null) => {
    if (group) {
      setSelectedGroup(group);
      setGroupForm({
        name: group.name,
        description: group.description,
        groupType: group.groupType,
        memberVehicles: [...group.memberVehicles],
        sharedPermissions: [...group.sharedPermissions]
      });
    } else {
      setSelectedGroup(null);
      setGroupForm({ name: '', description: '', groupType: '', memberVehicles: [], sharedPermissions: [] });
    }
    setOpenGroupDialog(true);
  };

  // 关闭车辆组对话框
  const handleCloseGroupDialog = () => {
    setOpenGroupDialog(false);
    setSelectedGroup(null);
    setGroupForm({ name: '', description: '', groupType: '', memberVehicles: [], sharedPermissions: [] });
  };

  // 提交车辆组表单
  const handleSubmitGroupForm = () => {
    const updatedGroups = [...vehicleGroups];
    
    if (selectedGroup) {
      // 更新现有车辆组
      const index = updatedGroups.findIndex(g => g.id === selectedGroup.id);
      if (index !== -1) {
        updatedGroups[index] = {
          ...updatedGroups[index],
          name: groupForm.name,
          description: groupForm.description,
          groupType: groupForm.groupType,
          memberVehicles: groupForm.memberVehicles,
          sharedPermissions: groupForm.sharedPermissions,
          updatedAt: new Date().toISOString()
        };
      }
    } else {
      // 添加新车辆组
      const newGroup = {
        id: `group${Date.now()}`,
        name: groupForm.name,
        description: groupForm.description,
        groupType: groupForm.groupType,
        memberVehicles: groupForm.memberVehicles,
        sharedPermissions: groupForm.sharedPermissions,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        createdBy: userData?.username || 'admin'
      };
      updatedGroups.push(newGroup);
    }
    
    setVehicleGroups(updatedGroups);
    localStorage.setItem('vehicleGroups', JSON.stringify(updatedGroups));
    handleCloseGroupDialog();
  };

  // 处理车辆组成员选择变化
  const handleMemberSelectionChange = (vehicleId) => {
    setGroupForm(prev => {
      if (prev.memberVehicles.includes(vehicleId)) {
        return {
          ...prev,
          memberVehicles: prev.memberVehicles.filter(id => id !== vehicleId)
        };
      } else {
        return {
          ...prev,
          memberVehicles: [...prev.memberVehicles, vehicleId]
        };
      }
    });
  };

  // 处理共享权限选择变化
  const handlePermissionSelectionChange = (permissionId) => {
    setGroupForm(prev => {
      if (prev.sharedPermissions.includes(permissionId)) {
        return {
          ...prev,
          sharedPermissions: prev.sharedPermissions.filter(id => id !== permissionId)
        };
      } else {
        return {
          ...prev,
          sharedPermissions: [...prev.sharedPermissions, permissionId]
        };
      }
    });
  };

  // 格式化时间戳
  const formatTimestamp = (timestamp) => {
    const date = new Date(timestamp);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // 获取车辆组类型文本
  const getGroupTypeText = (type) => {
    switch (type) {
      case 'logistics':
        return '物流车队';
      case 'taxi':
        return '出租车队';
      case 'mining':
        return '无人矿卡';
      case 'executive':
        return '高管专车';
      case 'private':
        return '私家车组';
      default:
        return type;
    }
  };

  // 获取车辆组类型图标
  const getGroupTypeIcon = (type) => {
    switch (type) {
      case 'logistics':
        return <DirectionsCar size={16} color="primary" />;
      case 'taxi':
        return <DirectionsCar size={16} color="secondary" />;
      case 'mining':
        return <DirectionsCar size={16} color="warning" />;
      case 'executive':
        return <DirectionsCar size={16} color="info" />;
      case 'private':
        return <DirectionsCar size={16} color="success" />;
      default:
        return <DirectionsCar size={16} color="default" />;
    }
  };

  // 获取权限名称
  const getPermissionName = (permissionId) => {
    const permission = availablePermissions.find(p => p.id === permissionId);
    return permission ? permission.name : '未知权限';
  };

  // 获取车辆信息
  const getVehicleInfo = (vehicleId) => {
    return allVehicles.find(v => v.id === vehicleId);
  };

  // 获取车辆状态样式
  const getStatusStyle = (status) => {
    switch (status) {
      case 'online':
        return { color: 'success.main' };
      case 'offline':
        return { color: 'error.main' };
      case 'warning':
        return { color: 'warning.main' };
      default:
        return { color: 'text.primary' };
    }
  };

  // 刷新数据处理函数
  const handleRefreshData = () => {
    setLoading(true);
    loadVehicleData().finally(() => {
      setLoading(false);
    });
  };

  // 查看详情处理函数
  const handleViewDetails = (group) => {
    // 这里可以实现查看详情的逻辑
    console.log('查看车辆组详情:', group);
    // 例如，可以打开一个详情对话框或者导航到详情页面
  };

  // 过滤车辆组
  const filteredGroups = vehicleGroups.filter(group => 
    group.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    group.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
    getGroupTypeText(group.groupType).toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <Box sx={{ p: 3 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 2 }}>
        <Typography variant="h4" component="h1" gutterBottom>
          <span style={{ display: 'flex', alignItems: 'center' }}>
            <NetworkCheck sx={{ mr: 2 }} />
            车辆内部组网
          </span>
        </Typography>
        <Button 
          variant="contained" 
          color="primary" 
          startIcon={<AddCircle />}
          onClick={() => handleOpenGroupDialog()}
        >
          创建车辆组
        </Button>
      </div>
      
      {loading && (
        <Typography variant="body1">加载数据中...</Typography>
      )}
      
      {error && (
        <div style={{ color: 'error.main', marginBottom: 2 }}>{error}</div>
      )}
      
      {!loading && (
        <>
          {/* 搜索和过滤区域 */}
          <Card sx={{ mb: 4 }}>
            <CardContent>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <TextField
                  label="搜索车辆组"
                  variant="outlined"
                  size="small"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  InputProps={{ startAdornment: <Search size="small" />, style: { width: 300 } }}
                />
                <Button variant="outlined" startIcon={<Refresh />} onClick={handleRefreshData}>
                  刷新数据
                </Button>
              </div>
            </CardContent>
          </Card>
          
          {/* 车辆组列表 */}
          {filteredGroups.length === 0 ? (
            <Typography variant="body1" align="center">暂无车辆组数据</Typography>
          ) : (
            <Grid container spacing={3}>
              {filteredGroups.map((group) => (
                <Grid item xs={12} md={6} key={group.id}>
                  <Card variant="outlined">
                    <CardContent>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 16 }}>
                        <div>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                            {getGroupTypeIcon(group.groupType)}
                            <Typography variant="h6">{group.name}</Typography>
                          </div>
                          <Typography variant="body2" color="text.secondary">
                            {getGroupTypeText(group.groupType)} | 创建于 {formatTimestamp(group.createdAt)}
                          </Typography>
                        </div>
                        <Button 
                          variant="text" 
                          color="primary"
                          size="small"
                          onClick={() => handleOpenGroupDialog(group)}
                        >
                          编辑
                        </Button>
                      </div>
                      
                      <Typography variant="body2" color="text.secondary" gutterBottom>
                        {group.description}
                      </Typography>
                      
                      {/* 组成员车辆 */}
                      <div style={{ marginBottom: 16 }}>
                        <Typography variant="subtitle2" gutterBottom>组成员车辆 ({group.memberVehicles.length}):</Typography>
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                          {group.memberVehicles.slice(0, 5).map((vehicleId) => {
                            const vehicle = getVehicleInfo(vehicleId);
                            return vehicle ? (
                              <Chip 
                                key={vehicleId} 
                                label={vehicle.licensePlate} 
                                size="small" 
                                variant="outlined"
                              />
                            ) : null;
                          })}
                          {group.memberVehicles.length > 5 && (
                            <Chip 
                              label={`+${group.memberVehicles.length - 5}`} 
                              size="small" 
                              variant="outlined"
                            />
                          )}
                        </div>
                      </div>
                      
                      {/* 共享权限 */}
                      <div style={{ marginBottom: 16 }}>
                        <Typography variant="subtitle2" gutterBottom>共享权限 ({group.sharedPermissions.length}):</Typography>
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                          {group.sharedPermissions.map((permissionId) => (
                            <Chip 
                              key={permissionId} 
                              label={getPermissionName(permissionId)} 
                              size="small" 
                              sx={{ backgroundColor: 'primary.light', color: 'primary.dark' }}
                            />
                          ))}
                        </div>
                      </div>
                      
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <Typography variant="caption" color="text.secondary">
                          最后更新: {formatTimestamp(group.updatedAt)}
                        </Typography>
                        <Button 
                          variant="contained" 
                          size="small" 
                          endIcon={<ChevronRight />}
                          onClick={() => handleViewDetails(group)}
                        >
                          查看详情
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                </Grid>
              ))}
            </Grid>
          )}
        </>
      )}
      
      {/* 车辆组对话框 */}
      <Dialog 
        open={openGroupDialog} 
        onClose={handleCloseGroupDialog}
        fullWidth
        maxWidth="md"
      >
        <DialogTitle>{selectedGroup ? '编辑车辆组' : '创建车辆组'}</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            margin="dense"
            label="车辆组名称"
            fullWidth
            value={groupForm.name}
            onChange={(e) => setGroupForm(prev => ({ ...prev, name: e.target.value }))}
          />
          <TextField
            margin="dense"
            label="描述"
            fullWidth
            multiline
            rows={3}
            value={groupForm.description}
            onChange={(e) => setGroupForm(prev => ({ ...prev, description: e.target.value }))}
          />
          <FormControl fullWidth margin="dense">
            <InputLabel>车辆组类型</InputLabel>
            <Select
              value={groupForm.groupType}
              onChange={(e) => setGroupForm(prev => ({ ...prev, groupType: e.target.value }))}
              label="车辆组类型"
            >
              <MenuItem value="">请选择类型</MenuItem>
              <MenuItem value="logistics">物流车队</MenuItem>
              <MenuItem value="taxi">出租车队</MenuItem>
              <MenuItem value="mining">无人矿卡</MenuItem>
              <MenuItem value="executive">高管专车</MenuItem>
              <MenuItem value="private">私家车组</MenuItem>
            </Select>
          </FormControl>
          
          {/* 组成员车辆选择 */}
          <div style={{ marginTop: 16 }}>
            <Typography variant="subtitle2" gutterBottom>选择组成员车辆:</Typography>
            <FormGroup>
              {allVehicles.map((vehicle) => (
                <FormControlLabel
                  key={vehicle.id}
                  control={
                    <Checkbox
                      checked={groupForm.memberVehicles.includes(vehicle.id)}
                      onChange={() => handleMemberSelectionChange(vehicle.id)}
                    />
                  }
                  label={
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span>{vehicle.licensePlate}</span>
                      <span style={{ fontSize: '0.75rem', color: 'text.secondary' }}>
                        ({vehicle.brand} {vehicle.model})
                      </span>
                      <span style={{ fontSize: '0.75rem' }}>
                        <span style={getStatusStyle(vehicle.status)}>
                          {vehicle.status === 'online' ? '在线' : '离线'}
                        </span>
                      </span>
                    </div>
                  }
                />
              ))}
            </FormGroup>
          </div>
          
          {/* 共享权限选择 */}
          <div style={{ marginTop: 16 }}>
            <Typography variant="subtitle2" gutterBottom>选择共享权限:</Typography>
            <FormGroup>
              {availablePermissions.map((permission) => (
                <FormControlLabel
                  key={permission.id}
                  control={
                    <Checkbox
                      checked={groupForm.sharedPermissions.includes(permission.id)}
                      onChange={() => handlePermissionSelectionChange(permission.id)}
                    />
                  }
                  label={
                    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8 }}>
                      <div>
                        <div>{permission.name}</div>
                        <div style={{ fontSize: '0.75rem', color: 'text.secondary' }}>
                          {permission.description}
                        </div>
                      </div>
                    </div>
                  }
                />
              ))}
            </FormGroup>
          </div>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseGroupDialog} startIcon={<Cancel />}>取消</Button>
          <Button onClick={handleSubmitGroupForm} startIcon={<Save />} color="primary">保存</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default VehicleNetworking;